<?php

namespace Util;

use Workerman\Http\Client;

class AsyncHttpUtil
{
    private static Client $http;

    public static function init(): void
    {
        $options = [
            'max_conn_per_addr' => 128, // 每个域名最多维持多少并发连接
            'keepalive_timeout' => 100,  // 连接多长时间不通讯就关闭
            'connect_timeout' => 600,  // 连接超时时间
            'timeout' => 300,  // 请求发出后等待响应的超时时间
        ];
        self::$http = new Client($options);
    }

    public static function request($url, $header, $data,$method = "POST", $success = null, $error = null)
    {
        self::init();
        if (!$error) {
            $error = function ($response) {
                echo $response->body;
            };
        }
        if (!$success) {
            $success = function ($response) {
                echo $response->body;
            };
        }
        LogUtil::debug($data);
        return self::$http->request($url, [
            'method' => $method,
            'version' => '1.1',
            'headers' => $header,
            'data' => $data,
            'success' => function ($response) use ($success) {
                $success($response->getBody());
                LogUtil::debug($response->getBody());
            },
            'error' => $error
        ]);
    }

    public static function get($url, $data,$header = [], $success=null, $error=null )
    {
        return self::request($url, $header, $data,"GET", $success, $error, );
    }

    public static function post($url, $data,$header = [], $success=null, $error=null )
    {
        return self::request($url, $header, $data,"POST", $success, $error, );
    }

    public static function postJson($url, $data, $success=null, $error=null,$header = [] )
    {
        $header["Content-Type"] = "application/json";
        return self::request($url, $header, $data,"POST", $success, $error, );
    }
}